/*******************************************************************************
 * Copyright (c) 2010 Jean-Michel Lemieux, Jeff McAffer, Chris Aniszczyk and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Hyperbola is an RCP application developed for the book
 *     Eclipse Rich Client Platform - 
 *         Designing, Coding, and Packaging Java Applications
 * See http://eclipsercp.org
 *
 * Contributors:
 *     Jean-Michel Lemieux and Jeff McAffer - initial API and implementation
 *     Chris Aniszczyk - edits for the second edition
 *******************************************************************************/
package org.rcp.collect.model;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.ListenerList;

public class DeviceGroup extends TreeItem implements IFolder {
	private List entries;

	private DeviceGroup parent;

	private String name;

	private ListenerList listeners;

	public DeviceGroup(DeviceGroup parent, String name) {
		this.name = name;
		this.parent = parent;
	}

	public String getName() {
		return name;
	}

	public DeviceGroup getParent() {
		return parent;
	}

	public void rename(String newName) {
		this.name = newName;
		fireContactsChanged(null);
	}

	public void addEntry(TreeItem entry) {
		if (entries == null)
			entries = new ArrayList(5);
		entries.add(entry);
		fireContactsChanged(null);
	}

	public void removeEntry(TreeItem entry) {
		if (entries != null) {
			entries.remove(entry);
			if (entries.isEmpty())
				entries = null;
		}
		fireContactsChanged(null);
	}

	public TreeItem[] getEntries() {
		if (entries != null)
			return (TreeItem[]) entries.toArray(new TreeItem[entries.size()]);
		return new TreeItem[0];
	}

	public void addContactsListener(IDeviceListener listener) {
		if (parent != null)
			parent.addContactsListener(listener);
		else {
			if (listeners == null)
				listeners = new ListenerList();
			listeners.add(listener);
		}
	}

	public void removeContactsListener(IDeviceListener listener) {
		if (parent != null)
			parent.removeContactsListener(listener);
		else {
			if (listeners != null) {
				listeners.remove(listener);
				if (listeners.isEmpty())
					listeners = null;
			}
		}
	}

	public void fireContactsChanged(TreeItem entry) {
		if (parent != null)
			parent.fireContactsChanged(entry);
		else {
			if (listeners == null)
				return;
			Object[] rls = listeners.getListeners();
			for (int i = 0; i < rls.length; i++) {
				IDeviceListener listener = (IDeviceListener) rls[i];
				listener.contactsChanged(this, entry);
			}
		}
	}
	
	public Presence getPresence() {
		return null;
	}
}
